import Dict from './Dict'
import type { App } from "vue";
import { DictConfig } from "@/framework/core/dict/types";
import { isFunction, isPromise } from '@/framework/utils/is';
const dictConfig: Record<string, DictConfig> = {}
const dictFiles = import.meta.globEager('/src/**/*.dict.ts');
Object.keys(dictFiles).forEach(async (path) => {
  if (path.startsWith('./index.')) return;
  const dictDefine = dictFiles[path].default;
  if (path.indexOf('allDict') > -1) {
    if (dictDefine['AllDict'] && dictDefine['AllDict'].data) {
      const res = await dictDefine['AllDict'].data()
      Object.keys(res).forEach(dictItem => {
        dictDefine[dictItem] = {
          data: res[dictItem],
          props: { ...(dictDefine['AllDict'].props || {}) }
        }
      })
    }
  }
  Object.keys(dictDefine).forEach(async key => {
    if (key === 'AllDict') {
      return
    }
    const data = dictDefine[key].data
    if (isFunction(data)) {
      const temp = data
      const tempResult = await temp()
      dictDefine[key].data = tempResult
    } else if (isPromise(data)) {
      const res = await data
      dictDefine[key].data = res
    }
    dictConfig[key] = dictDefine[key]
  })
});
export const dict = new Dict({
  // 异步数据最大缓存数
  max: 100,
  config: dictConfig
})

export const install = (app: App) => {
  app.config.globalProperties.$dict = dict;
  // app.config.globalProperties.$dict
};

export default install
